<template>
  <div class="container">
    <!-- 聊天区域 -->
    <div class="chat-area">
      <div class="content-display">
        <div v-for="(message, index) in messages" :key="index" class="message"
             :class="{ 'sender-message': message.senderId === userId,
                         'receiver-message': message.senderId !== userId }">
          <div class="message-content-wrapper">
            <el-avatar :src="message.senderId === userId ? senderAvatarUrl : receiverAvatarUrl" class="avatar"
                       v-if="senderAvatarUrl || receiverAvatarUrl"/>
            <div class="message-bubble">
              <!-- 修改这里，将AI用户名改为AI小助手 -->
              <div class="sender-name">{{ message.senderName }} {{ message.sendTime }}</div>
              <div class="bubble-content">{{ message.messageContent }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 输入区域 -->
    <div class="input-area">
      <textarea
          v-model="inputMessage"
          type="text"
          placeholder="输入消息..."
          class="message-input"
      />
      <button class="clear-button" @click="clearMessage">清空</button>
      <button class="send-button" @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted} from 'vue';
import {ElMessage} from "element-plus";
import {Client} from '@stomp/stompjs';
import SockJS from 'sockjs-client';
import axios from 'axios'; // 引入 axios

// 消息列表
const messages = ref([]);
const inputMessage = ref('');
// 头像
const senderAvatarUrl = ref('');
const receiverAvatarUrl = ref('');

// 清空消息
const clearMessage = () => {
  inputMessage.value = '';
};

// 获取当前用户的 ID和用户名
const userId = parseInt(localStorage.getItem('id'));
const userName = localStorage.getItem('username');

// WebSocket 相关
const socket = new SockJS('http://121.199.30.8:9937/ws');
const stompClient = new Client({
  webSocketFactory: () => socket,
  debug: function (str) {
    console.log(str);
  },
  // 设置连接超时时间为 5 秒
  connectHeaders: {
    'heart-beat': '5000,5000'
  },
  reconnectDelay: 5000 // 重连延迟 5 秒
});

// 进行连接
const connect = () => {
  stompClient.onConnect = (frame) => {
    console.log('连接成功: ' + frame);
    subscribeToDeepSeekResponse();
  };

  stompClient.onStompError = (frame) => {
    console.error('STOMP 连接错误:', frame);
    // 连接失败时尝试重连
    setTimeout(connect, stompClient.reconnectDelay);
  };

  stompClient.activate();
};

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim()) return;

  if (!stompClient.connected) {
    console.error('STOMP 连接未建立，无法发送消息');
    return;
  }

  // 创建本地消息对象
  const newMessage = {
    senderId: userId,
    senderName: userName,
    messageContent: inputMessage.value,
    sendTime: new Date().toLocaleString()
  };

  // 立即添加到消息列表
  messages.value.push(newMessage);

  // 创建一个空的 AI 消息对象
  const aiMessage = {
    senderId: 7,
    senderName: 'AI小助手',
    messageContent: '',
    sendTime: new Date().toLocaleString()
  };
  messages.value.push(aiMessage);

  // 通过 WebSocket 发送到 /app/sendMessageWithAI
  stompClient.publish({
    destination: `/app/sendMessageWithAI`,
    body: JSON.stringify({
      chatId: Math.min(userId, 7) + '_' + Math.max(userId, 7),
      senderId: userId,
      senderName: userName,
      receiverId: 7,
      receiverName: 'AI小助手',
      messageContent: inputMessage.value
    })
  });

  // 清空输入框
  inputMessage.value = '';

  // 滚动到底部
  setTimeout(() => {
    const contentDisplay = document.querySelector('.content-display');
    if (contentDisplay) {
      contentDisplay.scrollTop = contentDisplay.scrollHeight;
    }
  }, 0);
};

// 订阅 DeepSeek 响应
const subscribeToDeepSeekResponse = () => {
  const userId = localStorage.getItem('id');
  const chatId = Math.min(userId, 7) + '_' + Math.max(userId, 7);
  stompClient.subscribe(`/queue/private/${chatId}`, (message) => {
    const receivedMessage = JSON.parse(message.body);
    console.log('收到 DeepSeek 响应:', receivedMessage);

    // 查找最后一条 AI 消息
    let lastAssistantMessage = messages.value.findLast(m => m.senderId === 7);
    if (lastAssistantMessage) {
      const fullText = receivedMessage.messageContent;
      let currentIndex = 0;
      const typingInterval = setInterval(() => {
        if (currentIndex < fullText.length) {
          lastAssistantMessage.messageContent += fullText[currentIndex];
          currentIndex++;

          // 滚动到底部
          setTimeout(() => {
            const contentDisplay = document.querySelector('.content-display');
            if (contentDisplay) {
              contentDisplay.scrollTop = contentDisplay.scrollHeight;
            }
          }, 0);
        } else {
          clearInterval(typingInterval);
        }
      }, 25); // 每 50 毫秒显示一个字符，可以根据需要调整
    }
  });
};

// 加载聊天历史记录
const loadChatHistory = async () => {
  const userId = localStorage.getItem('id');
  const chatId = Math.min(userId, 7) + '_' + Math.max(userId, 7);
  try {
    const response = await axios.get(`/chat/history/AI/${chatId}`);
    if (response.data) { // 假设返回结果中 code 为 200 表示成功
      messages.value = response.data.data; // 将获取到的聊天记录添加到消息列表
      console.log('聊天历史记录加载成功:', messages.value);
    }
    //获取两者的头像
    const arr = chatId.split('_').map(Number);
    for (let i = 0; i < 2; i++) {
      const response_avatar = await axios.get('/user/getAvatar/' + arr[i])
      if (parseInt(localStorage.getItem('id')) === arr[i]) {
        senderAvatarUrl.value = response_avatar.data.data;
      } else {
        receiverAvatarUrl.value = response_avatar.data.data;
      }
    }
  } catch (error) {
    console.error('加载聊天历史记录失败:', error);
  }
};

// 组件挂载时进行连接和加载聊天历史记录
onMounted(() => {
  loadChatHistory().then(() => {
    // 滚动到底部
    setTimeout(() => {
      const contentDisplay = document.querySelector('.content-display');
      if (contentDisplay) {
        contentDisplay.scrollTop = contentDisplay.scrollHeight;
      }
    }, 0);
  });
  connect();
});

// 组件卸载时断开连接
onUnmounted(() => {
  stompClient.deactivate();
});
</script>

<style scoped>
/* 样式保持不变 */
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
}

.chat-area {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  padding: 20px;
  background-color: white;
}

.input-area {
  padding: 15px;
  display: flex;
  gap: 10px;
  align-items: center;
  border-top: 1px solid #ddd;
  background-color: #f9f9f9;
  flex-shrink: 0;
}

.message-input {
  flex: 1;
  min-height: 140px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  overflow-y: auto;
}

.clear-button {
  padding: 10px 15px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.clear-button:hover {
  background-color: #d32f2f;
}

.send-button {
  padding: 10px 15px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.send-button:hover {
  background-color: #0b7dda;
}

.content-display {
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message {
  display: flex;
  max-width: 80%;
}

.sender-message {
  align-self: flex-end;
  justify-content: flex-end;
}

.receiver-message {
  align-self: flex-start;
  justify-content: flex-start;
}

.message-content-wrapper {
  display: flex;
  align-items: flex-start; /* 修改这里，让头像上移 */
  gap: 8px;
  max-width: 100%;
}

.sender-message .message-content-wrapper {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;
}

.message-bubble {
  display: flex;
  flex-direction: column;
  max-width: 100%;
}

.sender-name {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
  padding: 0 4px;
  line-height: 1.2;
}

.sender-message .sender-name {
  text-align: right;
}

.receiver-message .sender-name {
  text-align: left;
}

.bubble-content {
  padding: 8px 12px;
  border-radius: 12px;
  word-wrap: break-word;
  line-height: 1.4;
  max-width: 100%;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.sender-message .bubble-content {
  background-color: #d4edda;
  color: #155724;
  border-top-right-radius: 2px;
}

.receiver-message .bubble-content {
  background-color: #e2e3e5;
  color: #383d41;
  border-top-left-radius: 2px;
}

/* 暗黑模式下的样式 */
[data-theme="dark"] .container {
  background-color: #121212;
  color: #fff;
}

[data-theme="dark"] .chat-area {
  background-color: black;
}

[data-theme="dark"] .input-area {
  background-color: #282828;
  border-top: 1px solid #333;
}

[data-theme="dark"] .message-input {
  background-color: #333;
  border: 1px solid #444;
  color: #fff;
}

[data-theme="dark"] .clear-button {
  background-color: #f44336;
  color: white;
}

[data-theme="dark"] .clear-button:hover {
  background-color: #d32f2f;
}

[data-theme="dark"] .send-button {
  background-color: #2196f3;
  color: white;
}

[data-theme="dark"] .send-button:hover {
  background-color: #0b7dda;
}

[data-theme="dark"] .content-display {
  color: #fff;
}

[data-theme="dark"] .message {
  color: #fff;
}

[data-theme="dark"] .sender-message .bubble-content {
  background-color: #007b00;
  color: #d4edda;
}

[data-theme="dark"] .receiver-message .bubble-content {
  background-color: #444;
  color: #e2e3e5;
}

[data-theme="dark"] .sender-name {
  color: #777;
}

[data-theme="dark"] .sender-name {
  color: #fff;
}

/* 添加过渡效果 */
[data-theme="dark"],
[data-theme="light"] {
  transition: background-color 0.3s, color 0.3s, border-color 0.3s; /* 添加过渡效果 */
}
</style>